<template>
  <el-row>
    <el-col>
      <el-form class="el-form-col" :model="model" label-position="left" ref="elForm" label-width="100px">
        <Portlet title="订单信息">
          <template slot="tools">
            <template v-if="routeName == 'orderCreateService' || routeName == 'orderEditService'">
              <el-button :loading="loading" class="btn-block" @click.prevent="submit" type="primary">立即下单</el-button>
              <el-button :loading="tempLoading" class="btn-block" @click.prevent="saveTemp" type="primary">保存至暂存单
              </el-button>
            </template>
          </template>
          <el-row :gutter="15">
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="仓储" prop="isStorage" :rules="[
                    {required: true, message: '仓储必须', trigger: 'change'}
                  ]">
                <el-switch
                  :disabled="isOrderEdit"
                  v-model="model.isStorage"
                  :active-value="1"
                  active-text="是"
                  inactive-text="否"
                  :inactive-value="0">
                </el-switch>
              </el-form-item>
            </el-col>

            <template v-if="model.isStorage">
              <el-col :md="12" :lg="8" :xl="6">
                <el-form-item label="仓储类型" prop="storageType" :rules="[
                    {required: true, message: '仓储类型必须', trigger: 'change'}
                  ]">
                  <el-radio-group :disabled="isOrderEdit" v-model="model.storageType">
                    <el-radio :key="item.value" v-for="item in cargoSourceTypes" :label="item.value">
                      {{ item.text }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :md="12" :lg="8" :xl="6">
                <el-form-item label="入库仓" prop="warehouseId" :rules="[
                      {required: true, message: '入库仓必须', trigger: 'change'}
                    ]">
                  <el-select clearable v-model="model.warehouseId" :disabled="isOrderEdit" placeholder="请选择入库仓">
                    <el-option v-for="item in warehouseIdArr" :key="item.value" :label="item.text"
                               :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </template>

            <!-- 选择型的商家: 长期仓储 -->
            <el-col v-if="model.storageType == 'CARGOSOURCETYPE01'" :md="12" :lg="8" :xl="6">
              <el-form-item label="商家名称" prop="cargoOwnerId" :rules="[
                    {required: true, message: '商家必须', trigger: 'change'}
                  ]">
                <el-select
                  v-model="model.cargoOwnerId"
                  :disabled="isOrderEdit"
                  filterable
                  clearable
                  placeholder="请输入关键词"
                  @focus="remoteQuery"
                  :loading="cargoOwnerLoading">
                  <el-option
                    v-for="item in cargoOwnerArr"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 建议型的商家 -->
            <el-col v-else :md="12" :lg="8" :xl="6">
              <el-form-item label="商家名称" prop="cargoOwnerName" :rules="[
                    {required: true, message: '商家必须', trigger: 'blur'}
                  ]">
                <el-autocomplete
                  :disabled="isOrderEdit"
                  v-model.trim="model.cargoOwnerName"
                  :fetch-suggestions="fetchSuggestionCargoOwnerName"
                  placeholder="请输入商家名称"
                  :trigger-on-focus="false"
                ></el-autocomplete>
                <span class="el-form-item__error"
                      v-if="autoCompleteCargoOwnerNameSuggest">{{ autoCompleteCargoOwnerNameSuggest }}</span>
              </el-form-item>
            </el-col>

            <!--<el-col :span="24">
              <p>
                <span v-if="!model.storageType" class="font-red" style="font-size: 14px; ">
                 （提示：请先选择上方货物来源类型后，才能选择相应的服务）
                </span>
                <span v-if="isOrderEdit" class="font-red" style="font-size:14px">
                  不可编辑
                </span>
              </p>
            </el-col>-->

            <el-col :span="24">
              <el-form-item
                label="业务类型"
                :rules="[
                  {required: true, message: '业务类型必须', trigger: 'change'}
                ]"
                prop="businessNo">
                <el-radio-group v-model="model.businessNo">
                  <el-radio
                    v-for="item in businessArr"
                    :label="item.value"
                    :key="item.value"
                    border>
                    {{ item.text }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item
                label="服务类型"
                :rules="[
                  {required: true, message: '服务类型必须', trigger: 'change'},
                  {validator: storeServiceRequired, message: '商城订单配送+安装必须', trigger: 'change'},
                ]"
                prop="serviceList">
                <el-checkbox-group class="checkbox-margin-left" v-model="model.serviceList">
                  <el-checkbox
                    v-for="item in serviceArr"
                    :label="item.serviceTypeCode"
                    :disabled="!serviceTypeEnable(item)"
                    :key="item.value"
                    border>
                    {{ item.serviceType }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>

          </el-row>
        </Portlet>

        <Portlet v-if="ifModule('goods')" title="商品信息">
          <ProductionSelectModal
            :value="model.productParameterList"
            :cargoOwnerId="model.cargoOwnerId"
            :cargoOwnerName="model.cargoOwnerName"
            :productType="model.productType"
            @addPackage="addPackage"
            :storageType="model.storageType"
            :visible.sync="outerVisible">
          </ProductionSelectModal>
          <template v-if="canEditProduction" slot="tools">
            <span v-if="hasAnyOverStorage" class="font-red"
                  style="font-size: 14px;">部分服务数量已经超过可用库存，需要新增入库订单补齐库存量后方可出库。</span>
            <el-button type="primary" @click.prevent="addProductList">添加商品</el-button>
          </template>
          <el-row :gutter="15">
            <el-col v-if="canEditProduction" :span="24">
              <el-form-item label-width="0" prop="productType" :rules="[
                {required: true, message: '产品类型必须', trigger: 'blur'}
              ]"
              >
                <el-radio-group v-model="model.productType">
                  <el-radio v-for="item in productTypeArrDisabled" :disabled="item.disabled" :key="item.value"
                            :label="item.value" border>
                    {{ item.text }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label-width="0" prop="productParameterList" :rules="[
                {required: true, message: '货物信息必须', trigger: 'change', type: 'array'}
             ]">
                <ProductionTable
                  :showShowOverStorage="showShowOverStorage"
                  :productType="model.productType"
                  v-model="model.productParameterList"
                  :showArriveNum="showArriveNum"
                />
              </el-form-item>
            </el-col>

            <el-col :sm="12" :md="6" :xl="6">
              <el-form-item label="总包件">
                <span>{{ computedTotalPackage }} 件</span>
              </el-form-item>
            </el-col>

            <el-col v-if="model.productType == 1" :sm="12" :md="6" :xl="6">
              <el-form-item label="建议体积">
                <span>{{totalVolume | decimalNumFilter}} m³</span>
              </el-form-item>
            </el-col>
            <!-- 单个体积计算有可能不正确，用户要自己修改总体积(李文龙) -->
            <el-col :sm="12" :md="6" :xl="6">
              <el-form-item
                prop="allVolume"
                :rules="[
                  {required: true, message: '总体积必须', trigger: 'change'},
                  {validator: isFormatNumber, int: 9,  message: '总体积必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                  {validator: range, min: 0.01,  message: '总体积必须大于0', trigger: 'blur'}
                ]"
                label="总体积">
                <el-input
                  :maxlength="50"
                  v-model="model.allVolume">
                  <template slot="append">
                    <el-button v-if="model.productType == 1" @click.prevent="suggestAllVolume">使用建议</el-button>
                    <span v-else>m³</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :sm="12" :md="6" :xl="6">
              <el-form-item prop="allWeight" :rules="[
                  {validator: isFormatNumber, int: 9,  message: '总重量必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                  {validator: range, min: 0.01,  message: '总重量必须大于0', trigger: 'blur'}
                ]" label="总重量">
                <el-input :maxlength="50" v-model="model.allWeight">
                  <template slot="append">kg</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </Portlet>

        <Portlet v-if="ifModule('consigneeInfo')" title="客户信息">
          <el-row :gutter="15">
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="客户姓名" prop="consigneName" :rules="[
                    {required: true, message: '客户姓名必须', trigger: 'blur'}
                  ]">
                <el-input :maxlength="50" v-model="model.consigneName"/>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="客户电话" prop="consignePhone" :rules="[
                    {required: true, message: '客户电话必须', trigger: 'blur'},
                    {validator: isPhone, message: '电话格式不正确', trigger: 'blur'},
                  ]">
                <el-input :maxlength="50" v-model="model.consignePhone"/>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="电梯" prop="elevator">
                <el-switch
                  v-model="model.elevator"
                  :active-value="1"
                  :inactive-value="0"
                  active-text="有"
                  inactive-text="无">
                </el-switch>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="楼层" prop="floor" :rules="[
                {validator: isInteger, message: '楼层必须是整数', type:'array', trigger: 'blur'}
              ]">
                <el-input :maxlength="3" v-model="model.floor"/>
              </el-form-item>
            </el-col>

            <el-col :md="24" :xl="12">
              <el-row :gutter="15">
                <el-col :md="12">
                  <el-form-item label="客户地址" prop="addressArr" :rules="[
                    {required: true, message: '客户地址必须', type:'array', trigger: 'change'}
                  ]">
                    <CascadeAddress v-model="model.addressArr" :level="3"/>
                  </el-form-item>
                </el-col>

                <el-col :md="12">
                  <el-form-item label-width="0" prop="consigneAddress" :rules="[
                    {required: true, message: '详细地址必须', trigger: 'blur'}
                  ]">
                    <el-input :maxlength="200" placeholder="详细地址" v-model="model.consigneAddress"/>
                  </el-form-item>
                </el-col>

                <el-col :md="12">
                  <el-form-item label="预约时间" prop="appointTime">
                    <el-date-picker class="el-form-col" :picker-options="pickerOptions" type="date" placeholder="选择年月日"
                                    v-model="model.appointTime" value-format="yyyy-MM-dd"></el-date-picker>
                  </el-form-item>
                </el-col>

                <el-col :md="12">
                  <el-form-item label-width="0" prop="appointTimePart" :rules="[
                    {validator: requiredIf, if () { return !!model.appointTime }, message: '请选择时间段', trigger: 'change'}
                  ]">
                    <el-radio-group style="min-width: 360px;" v-model="model.appointTimePart">
                      <el-radio v-for="item in timeCodeArr" :key="item.value" :label="item.value">{{ item.text }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>

            <el-col :md="24" :xl="12">
              <el-row :gutter="15">
                <el-col :span="24">
                  <el-form-item label="客户备注" prop="consigneMemo">
                    <el-input :maxlength="200" :rows="4" type="textarea" v-model="model.consigneMemo"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </Portlet>

        <Portlet v-if="hasPickUp && ifModule('pickUpInfo')" title="提货信息">
          <el-row :gutter="15">

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="是否到货" prop="orderPickUpInfo.doArrive" :rules="[
                    {required: true, message: '是否到货必须', trigger: 'blur'}
                  ]">
                <el-switch
                  v-model="model.orderPickUpInfo.doArrive"
                  active-value="1"
                  inactive-value="0"
                  active-text="是"
                  inactive-text="否">
                </el-switch>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="预计提货" prop="orderPickUpInfo.predictDevliveryDate">
                <el-date-picker :picker-options="pickerOptions" type="date" placeholder="选择年月日"
                                v-model="model.orderPickUpInfo.predictDevliveryDate"
                                value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="提货联系人" prop="orderPickUpInfo.pickUpName">
                <el-input :maxlength="50" v-model="model.orderPickUpInfo.pickUpName"/>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item :key="'pickUpPhone_' + model.orderPickUpInfo.doArrive" label-width="110px" label="提货电话"
                            prop="orderPickUpInfo.pickUpPhone" :rules="pickUpPhoneValidateRules">
                <el-input :maxlength="50" v-model="model.orderPickUpInfo.pickUpPhone"/>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item :key="'addressArr_' + model.orderPickUpInfo.doArrive" label="提货地址"
                            prop="orderPickUpInfo.addressArr" :rules="orderPickUpInfoAddressArrRules">
                <CascadeAddress v-model="model.orderPickUpInfo.addressArr" :level="3"/>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item :key="'pickUpAddress_' + model.orderPickUpInfo.doArrive" label="详细地址"
                            prop="orderPickUpInfo.pickUpAddress" :rules="orderPickUpInfoAddressRules">
                <el-input type="textarea" :maxlength="200" v-model="model.orderPickUpInfo.pickUpAddress"/>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="提货备注" prop="orderPickUpInfo.pickUpMemo">
                <el-input :maxlength="300" type="textarea" v-model="model.orderPickUpInfo.pickUpMemo"/>
              </el-form-item>
            </el-col>
          </el-row>
        </Portlet>

        <Portlet v-if="ifModule('costInfo')" title="费用信息">
          <div slot="tools">
            服务完成后，应付金额在结算报表中填写。
          </div>
          <el-row>
            <el-col :span="24">
              <el-table
                border
                max-height="500"
                :data="model.costList"
                :summary-method="getSummariesCostList"
                show-summary
                class="text-center"
              >
                <el-table-column
                  label="结算主体"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ cargoOwnerName }}
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="costName"
                  label="费用名称">
                  <template slot-scope="scope">
                    {{ scope.row.costName}}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="money"
                  width="240"
                  align="center"
                  label="应收金额">
                  <template slot-scope="scope">
                    <el-form-item label-width="0" :prop="'costList.' + scope.$index + '.money'" :rules="[
                      {validator: isFormatNumber, int: 9,  message: '应收金额必须是整数小于9位小数小于2位的小数', trigger: 'blur'}
                    ]">
                      <el-input v-model="scope.row.money" placeholder="0" label="应收金额"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </Portlet>

        <Portlet v-if="ifModule('boolCollectionInfo')" title="代收款">
          <template slot="tools">

            <el-popover
              placement="top-end"
              title="代收款说明"
              width="400"
              trigger="hover"
            >
              <ul style="list-style-type: decimal">
                <li>该单需要客户扫描支付成功后服务方方可签收；</li>
                <li>客户支付成功后代收金额进入钱包可以提现；</li>
                <li>每笔代收款有0.28%的手续费，由三方支付平台双乾支付收取。如代收1000.00元，客户支付1000.00元，钱包实际到账997.20元</li>
              </ul>
              <el-button slot="reference" type="text">代收款说明</el-button>
            </el-popover>

            <el-button type="primary" @click.prevent="addChServiceCollectionCostList">添加</el-button>
          </template>

          <el-row>
            <el-col :span="24">
              <el-table
                border
                max-height="500"
                :data="model.chServiceCollectionCostList"
                class="text-center"
                :summary-method="getSummariesChServiceCollectionCostList"
                show-summary
              >
                <el-table-column
                  label="结算主体"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ cargoOwnerName }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="productName"
                  align="center"
                  label="费用名称">
                  <template slot-scope="scope">
                    <el-form-item label-width="0" :prop="'chServiceCollectionCostList.' + scope.$index + '.costNo'">
                      <el-select v-model="scope.row.costNo">
                        <el-option :key="item.value" v-for="item in chServiceCollectionCostListAndDisable"
                                   :disabled="item.disabled" :label="item.text" :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="money"
                  align="center"
                  width="280"
                  label="应收金额">
                  <template slot-scope="scope">
                    <el-form-item label-width="0" :prop="'chServiceCollectionCostList.' + scope.$index + '.money'"
                                  :rules="[
                      {validator: isFormatNumber, int: 9,  message: '应收金额必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                      {validator: range, min: 0.01,  message: '应收金额必须大于0', trigger: 'blur'}
                    ]">
                      <el-input v-model="scope.row.money" label="应收金额"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="money"
                  align="center"
                  width="280"
                  label="代收备注">
                  <template slot-scope="scope">
                    <el-form-item label-width="0" :prop="'chServiceCollectionCostList.' + scope.$index + '.memo'">
                      <el-input v-model="scope.row.memo" label="代收备注" maxlength="50"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  width="240"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleDeleteChServiceCollectionCostList(scope.$index, scope.row)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </Portlet>

        <Portlet v-if="ifModule('verifyInfo')" title="核销">
          <el-row :gutter="15">
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="核销类型" prop="verifitySource">
                <el-select v-model="model.verifitySource">
                  <el-option value="" label="无需核销"></el-option>
                  <el-option
                    :key="item.value"
                    v-for="item in verifityNoList"
                    :label="item.text"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <template v-if="model.verifitySource">
              <el-col :md="12" :lg="8" :xl="6" :key="key" v-for="(item, key) in model.verifityNoList">
                <el-form-item label="核销单号" prop="memo">
                  <el-input :maxlength="200" v-model="item.code">
                    <template slot="append" v-if="model.verifityNoList.length > 1">
                      <i class="el-icon-delete font-red" @click.prevent="removeVerifityNoList(key)"></i>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :md="12" :lg="8" :xl="6">
                <el-form-item label-width="0">
                  <el-button @click.prevent="pushVerifityNoList" type="text">添加单号</el-button>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </Portlet>

        <Portlet v-if="ifModule('otherInfo')" title="其他信息">
          <span slot="tools">
            填写接单价或者总货值后，在《我的毛利报表》中可以展示出相关的数据
          </span>
          <!---->
          <el-row :gutter="15">

            <!--将原"派单工号"改为：来源单号-->
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="外部单号" prop="orderSourceNo">
                <el-input :maxlength="200" v-model="model.orderSourceNo"/>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item
                label="接单价"
                :rules="[
                  {validator: isFormatNumber, int: 9,  message: '接单价必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                  {validator: range, min: 0.01,  message: '接单价必须大于0', trigger: 'blur'}
                ]"
                prop="pickOrderMoney">
                <el-input v-model="model.pickOrderMoney">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item
                label="总货值"
                :rules="[
                  {validator: isFormatNumber, int: 9,  message: '总货值必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                  {validator: range, min: 0.01,  message: '总货值必须大于0', trigger: 'blur'}
                ]"
                prop="cargoPrice">
                <el-input :maxlength="200" v-model="model.cargoPrice">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>

            <!-- 如果是暂存单 显示来源-->
            <el-col v-if="isTempService" :md="12" :lg="8" :xl="6">
              <el-form-item label="推单来源">
                <span style="height: 42px; display: inline-block">{{ model.outSourceWarehouse }}</span>
              </el-form-item>
            </el-col>

            <!-- 如果是暂存单 显示来源-->
            <el-col v-if="isTempService" :md="12" :lg="8" :xl="6">
              <el-form-item label="推单来源单号">
                <span style="height: 42px; display: inline-block">{{ model.outNo }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="订单备注" prop="memo">
                <el-input type="textarea" :maxlength="200" v-model="model.memo"/>
              </el-form-item>
            </el-col>
          </el-row>
        </Portlet>

        <Portlet>
          <el-row>
            <el-col :span="24" class="text-center">
              <template v-if="routeName == 'orderCreateService' || routeName == 'orderEditService'">
                <el-button :loading="loading" class="btn-block" @click.prevent="submit" type="primary">立即下单</el-button>
                <el-button :loading="tempLoading" class="btn-block" @click.prevent="saveTemp" type="primary">保存至暂存单
                </el-button>
              </template>

              <template v-if="routeName == 'orderTempServiceShow'">
                <el-button :loading="loading" class="btn-block" @click.prevent="submit" type="primary">提交</el-button>
                <el-button :loading="saveLoading" class="btn-block" @click.prevent="save" type="primary">保存</el-button>
              </template>

              <template v-if="isOrderEdit">
                <el-button :loading="loading" class="btn-block" @click.prevent="submit" type="primary">提交</el-button>
              </template>

              <template v-if="isStoreOrder">
                <el-button :loading="loading" @click.prevent="toStoreIndex">取消</el-button>
                <el-button :loading="loading" @click.prevent="submit" type="primary">立即发货</el-button>
              </template>
            </el-col>
          </el-row>
        </Portlet>
      </el-form>
    </el-col>
  </el-row>
</template>
<script>
import ProductionSelectModal from '@/views/oms/order/ProductionSelectModal'
import ProductionTable from '@/views/oms/order/ProductionTable'
import {
  getCargoSourceType,
  getSubDictListOfParentCode,
  getChCollectionCost,
  getTimeInterval,
  getMyWarehouse,
  getOmsBusinessList,
  getOmsCreateServiceList,
  getOmsModuleIf
} from '@/utils/selectOptions'
import {copy, dotData, alert, isEqual, confirm, arrayColumn} from '@/utils'
import {isPhone, isInteger, isFormatNumber, range, requiredIf} from '@/utils/validate'
import {filterDataBaseDictionary, decimalNumFilter, unixTimestampFilter} from '@/filters'
import moment from 'moment'
import L from 'lodash'

export default {
  components: {
    ProductionSelectModal,
    ProductionTable
  },
  filters: {
    filterDataBaseDictionary,
    decimalNumFilter
  },
  data() {
    return {
      id: this.$route.params.id,
      routeName: this.$route.name,
      outerVisible: false,
      loading: false,
      tempLoading: false,
      model: {
        warehouseId: '',
        productParameterList: [],
        storageType: '',
        cargoOwnerId: '',
        cargoOwnerName: '',
        serviceList: [],
        consigneName: '',
        consignePhone: '',
        floor: '',
        consigneMemo: '',
        addressArr: [],
        consigneAddress: '',
        outNo: '',
        outSourceWarehouse: '',
        memo: '',
        productType: 3,
        elevator: 0,
        costList: [],
        orderPickUpInfo: {
          pickUpAddress: '',
          addressArr: [],
          pickUpMemo: '',
          pickUpName: '',
          pickUpPhone: '',
          doArrive: '',
          predictDevliveryDate: ''
        },
        chServiceCollectionCostList: [],
        appointTime: '',
        appointTimePart: '',
        verifityNoList: [{code: ''}],
        verifitySource: '', // 核销类型
        isStorage: 0, // 是否有仓库
        allVolume: '',
        businessNo: '',
        cargoPrice: '',
        pickOrderMoney: '',
        allWeight: '',
        orderSourceNo: '' // 推单单号
      },
      cargoOwnerArr: [],
      cargoOwnerLoading: false,
      cargoSourceTypes: [],
      initLoading: false,
      saveLoading: false,
      serviceTypeArr: [],
      serviceTypeObj: {},
      businessArr: [],
      serviceArr: [],
      pickerOptions: {
        disabledDate(time) {
          return moment(time).isBefore(Date.now(), 'day')
        }
      },
      // 时间段选项
      timeCodeArr: [],
      // 代收款费用
      chServiceCollectionCostList: [],
      // 仓库数组
      warehouseIdArr: [],
      // 核销类型
      verifityNoList: [],
      // 推单来源
      outSourceWarehouse: '',
      // 要展示的模块
      modules: null,
      mallOrderId: '', // 商城id
      productTypeArr: [ // 产品类别
        {value: 3, text: '自定义产品'},
        {value: 1, text: '标准产品'},
        {value: 2, text: '通用产品'}
      ],
      autoCompleteCargoOwnerNameSuggest: ''
    }
  },
  computed: {
    productTypeArrDisabled() {
      return this.productTypeArr.map(v => {
        let disabled = this.model.storageType === 'CARGOSOURCETYPE01' && v.value !== 1
        if (this.isOrderEdit) { // 订单修改不能修改订单类型
          disabled = true
        }
        return Object.assign({}, v, {
          disabled
        })
      })
    },
    hasAnyOverStorage() {
      if (this.showShowOverStorage) {
        let tempMap = new Map()
        if (Array.isArray(this.model.productParameterList)) {
          for (let v of this.model.productParameterList) {
            if (!tempMap.has(v.productId)) {
              tempMap.set(v.productId, 0)
            }
            tempMap.set(v.productId, tempMap.get(v.productId) + v.num)
            if (tempMap.get(v.productId) > v.availableNum) {
              return true
            }
          }
        }
      }
      return false
    },
    // 是否是商城订单
    isStoreOrder() {
      return this.routeName === 'shopDelivery'
    },
    // 选中的服务类型
    checkedServiceType() {
      return this.model.serviceList
    },
    // 选中的服务类型对应的费用
    checkedServiceTypeCostList() {
      return this.serviceArr
        .filter(v => this.model.serviceList.indexOf(v.serviceTypeCode) >= 0).reduce((total, item) => {
          if (Array.isArray(item.costList)) {
            return total.concat(item.costList)
          }
          return total
        }, [])
    },
    // 可选的服务类型
    checkedEnableCode() {
      if (Array.isArray(this.serviceArr)) {
        return this.serviceArr
          .filter(v => this.model.serviceList.indexOf(v.serviceTypeCode) >= 0)
          .reduce((total, item) => {
            if (Array.isArray(item.ableCodes)) {
              return total.concat(item.ableCodes)
            }
            return total
          }, [])
      }
      return []
    },
    // 不可选类型
    checkedDisableCode() {
      if (Array.isArray(this.serviceArr)) {
        return this.serviceArr
          .filter(v => this.model.serviceList.indexOf(v.serviceTypeCode) >= 0)
          .reduce((total, item) => {
            if (Array.isArray(item.disableCodes)) {
              return total.concat(item.disableCodes)
            }
            return total
          }, [])
      }
      return []
    },
    // 商家名称
    cargoOwnerName() {
      let id = this.model.cargoOwnerId
      let list = this.cargoOwnerArr
      if (Array.isArray(list)) {
        for (let v of list) {
          if (v.value === id) {
            return v.text
          }
        }
      }
      if (this.model.cargoOwnerName) {
        return this.model.cargoOwnerName
      }
      return id
    },
    // 能设置产品类型
    canSetProductType() {
      // CARGOSOURCETYPE02 快进快出 CARGOSOURCETYPE03:上门服务
      if (this.isOrderEdit) { // 编辑模式不可修改
        return false
      }
      if (!this.model.isStorage) { // 无仓库都可选择
        return true
      }
      return ['CARGOSOURCETYPE02', 'CARGOSOURCETYPE03'].indexOf(this.model.storageType) >= 0
    },
    // 有提货信息
    hasPickUp() {
      return this.checkedServiceType.indexOf('CHADDEDEDSERVICE06') >= 0
    },
    // 那些需要判断是否要超库存
    showShowOverStorage() {
      return ['CARGOSOURCETYPE01'].indexOf(this.model.storageType) >= 0
    },
    // 是否有代收货款
    hasChServiceCollectionCostList() {
      return true
    },
    // 带有禁用的 费用选项
    chServiceCollectionCostListAndDisable() {
      // disabled
      let temp = arrayColumn(this.model.chServiceCollectionCostList, 'costNo')
      return this.chServiceCollectionCostList.map(v => {
        if (temp.indexOf(v.value) >= 0) {
          v.disabled = true
        } else {
          v.disabled = false
        }
        return v
      })
    },
    // 是否有入库仓
    hasWarehouseId() {
      return !!this.model.isStorage
    },
    // 是否展示产品到件数量
    showArriveNum() {
      return this.isOrderEdit
    },
    isOrderEdit() { // 正常订单编辑
      return this.routeName === 'orderServiceOrdersEdit'
    },
    isTempService() { // 服务暂存单
      return this.routeName === 'orderTempServiceShow'
    },
    // 商家名称需要收货仓编号
    cargoOwnerIdNeedWarehouseId() {
      if (this.model.isStorage) {
        return ['CARGOSOURCETYPE01'].indexOf(this.model.storageType) >= 0
      } else {
        return false
      }
    },
    // 标准产品的总体积
    totalVolume() {
      return this.model.productParameterList.reduce((total, v) => {
        return total + (Number(v.volume) || 0) * (Number(v.num) || 0)
      }, 0)
    },
    // 能选中服务类型
    canCheckServiceCode() {
      if (this.model.businessNo && [1, 0].indexOf(this.model.isStorage) >= 0) {
        if (this.model.isStorage === 1) { // 有仓库就要仓库类型
          if (this.model.storageType) {
            return true
          }
        } else {
          return true
        }
      }
      return false
    },
    // 总包件数
    computedTotalPackage() {
      return this.model.productParameterList.reduce((total, item) => {
        const num = parseInt(item.packNum)
        if (num) {
          return total + num
        }
        return total
      }, 0)
    },
    // 能修改产品信息
    canEditProduction() {
      return !this.isStoreOrder
    },
    // 提货人电话验证规则
    pickUpPhoneValidateRules() {
      let temp = [
        {validator: isPhone, message: '电话格式不正确', trigger: 'blur'}
      ]
      const doArrive = dotData(this.model, 'orderPickUpInfo.doArrive')
      if (parseInt(doArrive) === 1) {
        return [
          ...temp,
          {required: true, message: '提货电话必须', trigger: 'blur'}
        ]
      }
      return temp
    },
    // 提货地址验证规则
    orderPickUpInfoAddressArrRules() {
      const doArrive = dotData(this.model, 'orderPickUpInfo.doArrive')
      if (parseInt(doArrive) === 1) {
        return [
          {required: true, message: '提货地址必须', type: 'array', trigger: 'change'}
        ]
      }
      return []
    },
    // 提货地址验证规则
    orderPickUpInfoAddressRules() {
      const doArrive = dotData(this.model, 'orderPickUpInfo.doArrive')
      if (parseInt(doArrive) === 1) {
        return [
          {required: true, message: '详细地址必须', trigger: 'blur'}
        ]
      }
      return []
    }
  },
  watch: {
    'model.storageType'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (this.initLoading) {
        return
      }
      if (val === 'CARGOSOURCETYPE02') { // 若勾选的商家来源为：快进快出--> 下面类型自动选为 自定义
        this.model.productType = 3
      } else if (val === 'CARGOSOURCETYPE01') { // 长期仓储 选择标准产品
        this.model.productType = 1
      }
      /* 已经移除
      if (val === 'CARGOSOURCETYPE03') { // 若勾选的商家来源为：上门--> 下面类型 默认为 标准产品
        this.model.productType = 1
      }*/
      this.model.cargoOwnerId = ''
      this.model.cargoOwnerName = ''
      this.cargoOwnerArr = []
      // 设置服务类型
      this.setServiceArr()
    },
    'model.isStorage'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (this.initLoading) {
        return
      }
      // 没有仓储产品类型选择自定义
      if (!val) {
        this.model.productType = 3
      }
      // 清空客户信息
      this.model.cargoOwnerId = ''
      this.cargoOwnerArr = []
      // 设置服务类型
      this.setServiceArr()
      // 获取仓库
      // 根据入库类型来
      this.model.warehouseId = ''
      if (val) {
        if (this.warehouseIdArr.length === 0) {
          confirm('如需使用仓库，则需要先维护仓库的基础资料信息', '温磬提示', {
            confirmButtonText: '前往设置',
            cancelButtonText: '暂时跳过',
            type: 'warning'
          }).then(_ => {
            this.$router.push({path: '/ss-oms/warehouse/configuration/index'})
          }).catch(_ => {
            console.log('取消设置仓库')
          })
        }
      }
      this.model.storageType = ''
    },
    'model.warehouseId'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (this.initLoading) {
        return
      }
      // 清空商家信息
      if (this.cargoOwnerIdNeedWarehouseId) {
        this.model.cargoOwnerId = ''
        this.cargoOwnerArr = []
      }
    },
    'model.businessNo'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (this.initLoading) {
        return
      }
      // 设置服务类型
      this.setServiceArr()
      // 设置模块展示
      this.setModuleIf()
    },
    warehouseIdArr(val, oldVal) {
      // 只有一个时默认选中
      if (Array.isArray(val) && val.length === 1) {
        this.model.warehouseId = val[0].value
      }
    },
    'model.productType'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (this.initLoading) {
        return
      }
      this.model.productParameterList = []
    },
    'model.serviceList'(val, oldVal) {
      if (isEqual(val, oldVal)) {
        return
      }
      if (this.initLoading) {
        return
      }
      // 设置增值费
      this.setModelFee(this.checkedServiceTypeCostList)
      // 展示模块
      this.setModuleIf()
    },
    canSetProductType(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (this.initLoading) {
        return
      }
      if (val === false) {
        this.model.productType = 1
      }
    },
    'model.appointTime'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (this.initLoading) {
        return
      }
      if (!val) {
        this.model.appointTimePart = ''
      }
    },
    'model.cargoOwnerName'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (this.initLoading) {
        return
      }
      this.model.cargoOwnerId = ''
      this.blurSetCargoOwnerName()
    }
  },
  created() {
    getCargoSourceType().then(arr => {
      this.cargoSourceTypes = arr
    })
    getTimeInterval().then(arr => {
      this.timeCodeArr = arr
    })
    getSubDictListOfParentCode('FHBHXLX').then(arr => {
      this.verifityNoList = arr
    })
    // 业务类型
    getOmsBusinessList().then(arr => {
      this.businessArr = arr
    }).then(_ => {
      if (!this.id) {
        if (this.businessArr.length === 1) {
          this.model.businessNo = dotData(this.businessArr, '[0].value')
        }
      }
    })
    // 获取所有的服务类型
    getSubDictListOfParentCode('ZpsServiceType').then(arr => {
      this.serviceArr = arr.map(v => {
        v.serviceTypeCode = v.value
        v.serviceType = v.text
        v.disabled = true
        return v
      })
    })
    if (this.id) {
      if (this.routeName === 'orderTempServiceShow') { // 暂存详情
        this.getTempDetail()
      } else if (this.routeName === 'orderServiceOrdersEdit') { // 正式订单详情
        this.getOrderDetail()
      } else if (this.isStoreOrder) { // 获取商城订单服务单详情
        this.getStoreOrderDetail()
      }
    }
    // 代收货款
    getChCollectionCost().then(arr => {
      if (Array.isArray(arr)) {
        this.chServiceCollectionCostList = arr
      }
    })
    // 获取仓库信息
    getMyWarehouse().then(arr => {
      this.warehouseIdArr = arr
    }).then(_ => {
      if (!this.id) { // 编辑界面以后端数据为主
        // 当没有设置仓库基础资料的时候仓储默认选择“否”，当有仓库基础资料后仓储默认选择“是”
        if (this.warehouseIdArr.length > 0) {
          this.model.isStorage = 1
        } else {
          this.model.isStorage = 0
        }
      }
    })
  },
  methods: {
    isPhone,
    isInteger,
    isFormatNumber,
    range,
    requiredIf,
    storeServiceRequired(rule, value, callback) {
      if (!this.storeOrder) {
        callback()
        return
      }
      // ZpsServiceType01: 配送 ZpsServiceType02: 安装
      if (Array.isArray(value) && value.indexOf('ZpsServiceType01') >= 0 && value.indexOf('ZpsServiceType02') >= 0) {
        callback()
      }
      callback(new Error(rule.message || rule.field + '不是一个整型'))
    },
    remoteMethod: L.debounce((query, _this) => {
      if (!query) {
        _this.cargoOwnerLoading = false
        return
      }
      this.$ajax.get('/ms-warehouse-order/WhPackage/findCargoOwner', {
        cargoOwnerName: query,
        storageType: _this.model.storageType
      }).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          let tempArr = []
          if (Array.isArray(data)) {
            data.forEach((v, k) => {
              tempArr.push({
                text: v.cargoOwnerName,
                value: v.cargoOwnerId
              })
            })
          }
          _this.cargoOwnerArr = tempArr
        }
      }).finally(_ => {
        _this.cargoOwnerLoading = false
      })
    }, 1000),
    remoteQuery(query) {
      if (this.model.isStorage && !this.model.storageType) {
        alert('请先选择仓储类型')
        return
      }
      if (this.cargoOwnerIdNeedWarehouseId) {
        if (!this.model.warehouseId) {
          alert('请先选择入库仓')
          return
        }
      }
      this.cargoOwnerLoading = true
      // this.remoteMethod(query, this) 这里是输入建议改为获取前端过滤
      this.httpGetCargoOwnerAll().then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          let tempArr = []
          if (Array.isArray(data)) {
            data.forEach((v, k) => {
              tempArr.push({
                text: v.cargoOwnerName,
                value: v.cargoOwnerId
              })
            })
          }
          this.cargoOwnerArr = tempArr
        }
      }).finally(_ => {
        this.cargoOwnerLoading = false
      })
    },
    // 建议输入的方法
    fetchSuggestionCargoOwnerName(queryString, cb) {
      if (!queryString) {
        return
      }
      this.httpGetCargoOwnerAll(queryString).then(response => {
        let temp = []
        if (Array.isArray(response.data)) {
          temp = response.data.map(v => {
            v.value = v.cargoOwnerName
            return v
          })
        }
        cb(temp)
      }).catch(_ => {
        const suggest = []
        cb(suggest)
      })
    },
    httpGetCargoOwnerAll(cargoOwnerName = '') {
      let params = {}
      if (this.model.isStorage) { // 有仓库才有以下参数 storageType
        params.storageType = this.model.storageType
        if (this.model.warehouseId) {
          params.warehouseId = this.model.warehouseId
        }
      }
      if (cargoOwnerName) { // 搜索的字段
        params.cargoOwnerName = cargoOwnerName
      }
      return this.$ajax.get('/ms-warehouse-order/WhPackage/findCargoOwner', params)
    },
    httpPost(url) {
      let data = copy(this.model, true)
      let productParameterList = []
      if (Array.isArray(data.productParameterList)) {
        data.productParameterList.forEach(v => {
          let temp = {
            productId: v.productId,
            num: v.num,
            roomArea: v.roomArea,
            packNum: v.packNum,
            installFee: v.installFee,
            memo: v.memo,
            middleClassNo: v.middleClassNo,
            bigClassNo: v.bigClassNo
          }
          if (data.productType === 3) { // 自定义产品
            temp.productName = v.productName
            temp.manufacturersName = v.manufacturersName
            if (v.productIsTwo) {
              temp.productIsTwo = v.productIsTwo
            }
            if (v.manufacturersId) {
              temp.manufacturersId = v.manufacturersId
            }
          }
          // 如果有到件数量添加上
          if (v.arriveNum) {
            temp.arriveNum = v.arriveNum
          }
          productParameterList.push(temp)
        })
      }
      data.productParameterList = productParameterList
      // 代收货款处理 有且选中了代收货款
      if (this.hasChServiceCollectionCostList) {
        data.chServiceCollectionCostList = data.chServiceCollectionCostList.filter(v => {
          return !!L.trim(v.money)
        })
      } else {
        data.chServiceCollectionCostList = []
      }
      // 省市区处理
      if (Array.isArray(data.addressArr)) {
        data.consigneProvinceNo = dotData(data.addressArr, 0)
        data.consigneCityNo = dotData(data.addressArr, 1)
        data.consigneDistrictNo = dotData(data.addressArr, 2)
        delete data.addressArr
      }
      // 费用处理
      if (Array.isArray(data.costList)) {
        data.costList.forEach(v => {
          if (!v.money) {
            v.money = 0
          }
          v.clearingObject = data.cargoOwnerId
        })
      }
      // 提货信息处理
      if (this.hasPickUp) {
        data.orderPickUpInfo.pickUpProvinceNo = dotData(data, 'orderPickUpInfo.addressArr[0]')
        data.orderPickUpInfo.pickUpCityNo = dotData(data, 'orderPickUpInfo.addressArr[1]')
        data.orderPickUpInfo.pickUpDistrictNo = dotData(data, 'orderPickUpInfo.addressArr[2]')
        delete data.orderPickUpInfo.addressArr
      } else {
        delete data.orderPickUpInfo
      }
      // 核销单号
      if (data.verifitySource) {
        if (Array.isArray(data.verifityNoList)) {
          data.verifityNoList = data.verifityNoList.map(v => v.code)
        } else {
          data.verifityNoList = []
        }
      } else {
        data.verifityNoList = []
      }
      // 总体积
      data.allVolume = data.allVolume ? data.allVolume : decimalNumFilter(this.totalVolume)
      if (data.allVolume === '') {
        alert('总体积必须')
        return
      }
      // 仓库类型
      if (!data.isStorage) { // 没有仓库，就没有仓库类型
        data.storageType = ''
      }
      if (this.id) { // 转正
        if (this.routeName === 'orderTempServiceShow') { // 暂存单
          data.orderId = this.id
        }
        if (this.isOrderEdit) { // 订单编辑
          data.isEdit = 1
          data.orderId = this.id
        }
        if (this.isStoreOrder) { // 商城订单给出相关商城订单id
          data.mallOrderId = this.mallOrderId
        } else {
          data.id = this.id
        }
      }
      return this.$ajax.post(url, data)
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        let title = ''
        if (this.id) { // 转正
          title = '提交成功'
        } else {
          title = '添加成功'
        }
        this.loading = true
        this.httpPost('/ms-warehouse-order/service-order-controller/save-service-order').then(response => {
          const success = dotData(response, 'success')
          if (success) {
            this.$confirm(title, title, {
              type: 'success',
              showCancelButton: false,
              closeOnClickModal: false
            }).then(_ => {
              if (this.id) { // 转正后
                // 如何是编辑订单
                if (this.isOrderEdit) { // 正式订单
                  this.$router.push({path: '/redirect/ss-oms/orders/service-orders/edit-index'})
                } else if (this.isTempService) { // 暂存服务单
                  this.$router.push({path: '/redirect/ss-oms/order/temp-service'})
                } else if (this.isStoreOrder) { // 商城服务单
                  this.toStoreIndex()
                }
              } else {
                this.resetFields()
              }
            }).finally(_ => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    // 重置表单
    resetFields() {
      try {
        this.autoCompleteCargoOwnerNameSuggest = ''
        this.$refs.elForm.resetFields()
      } catch (err) {
        console.log(err)
      }
    },
    // 暂存单保存
    save() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        this.saveLoading = true
        this.httpPost('/ms-warehouse-order/orderTemp/saveServiceOrderTemp').then(response => {
          const success = dotData(response, 'success')
          if (success) {
            this.$confirm('暂存单保存成功', undefined, {
              type: 'success',
              showCancelButton: false,
              closeOnClickModal: false
            }).finally(_ => {
              this.saveLoading = false
              if (this.routeName === 'orderTempServiceShow') {
                this.$router.push({path: '/redirect/ss-oms/order/temp-service'})
              }
            })
          } else {
            this.saveLoading = false
          }
        }).catch(_ => {
          this.saveLoading = false
        })
      })
    },
    saveTemp() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          return
        }
        this.tempLoading = true
        this.httpPost('/ms-warehouse-order/service-order-controller/save-service-order-temp').then(response => {
          const success = dotData(response, 'success')
          if (success) {
            confirm('保存成功', undefined, {type: 'success'}).then(_ => {
              this.$router.push({path: '/redirect/ss-oms/order/temp-service'})
            }).finally(_ => {
              this.resetFields()
              this.tempLoading = false
            })
          } else {
            this.tempLoading = false
          }
        }).catch(_ => {
          this.tempLoading = false
        })
      })
    },
    // 添加产品
    addPackage(arr) {
      let tempMap = new Map()
      this.model.productParameterList.forEach(v => {
        tempMap.set(v.productId, v)
      })
      arr.forEach(v => {
        if (!tempMap.has(v.productId)) {
          this.$set(v, 'num', 1)
          this.$set(v, 'roomArea', '')
          this.$set(v, 'installFee', '')
          this.$set(v, 'packNum', 1)
          this.model.productParameterList.push(v)
        } else {
          let item = tempMap.get(v.productId)
          this.$set(item, 'num', item.num ? item.num + 1 : 1)
          this.$set(item, item.packNum ? item.packNum + 1 : 1)
        }
      })
    },
    addProductList() {
      if (this.model.productType === 3) {
        this.model.productParameterList.push({
          manufacturersName: '',
          productNo: '提交后生成',
          availableNum: '/',
          productUnit: '',
          installFee: '',
          packNum: 1
        })
      } else {
        /*
        if (!this.model.cargoOwnerId) {
          alert('请先选择商家')
          return
        }*/
        this.outerVisible = true
      }
    },
    // 根据服务类型设置费用
    setModelFee(list) {
      // 移除多余的费用
      const codeArr = list.map(v => v.code)
      this.model.costList = this.model.costList.filter(v => codeArr.indexOf(v.code) >= 0)
      // 添加新的费用
      const modelCodeArr = this.model.costList.map(v => v.code)
      const newList = list.filter(v => modelCodeArr.indexOf(v.code) < 0).reduce((total, v) => {
        return total.concat([{
          costName: v.costName,
          code: v.code,
          serviceNo: v.serviceNo,
          money: ''
        }])
      }, [])
      this.model.costList = this.model.costList.concat(newList)
    },
    // 服务类型的禁用与允许
    serviceTypeEnable(item) {
      // 如果是正式订单编辑则不允许修改
      if (this.isOrderEdit) {
        return false
      }
      // 有服务code ?
      if (!(item && item.serviceTypeCode)) {
        return false
      }
      // 一旦包含禁止则禁用 serviceTypeCode
      if (this.checkedDisableCode.indexOf(item.serviceTypeCode) >= 0) {
        return false
      }
      // 有启用的就需要启用
      if (this.checkedEnableCode.indexOf(item.serviceTypeCode) >= 0) {
        return true
      }
      return parseInt(item.choosable) === 1
    },
    // 删除代收款费用
    handleDeleteChServiceCollectionCostList(index) {
      this.model.chServiceCollectionCostList.splice(index, 1)
    },
    // 添加代收款
    addChServiceCollectionCostList() {
      this.model.chServiceCollectionCostList.push({
        costNo: '',
        money: ''
      })
    },
    // 代收款合计
    getSummariesChServiceCollectionCostList(param) {
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]))
        if (index === 0) {
          sums[index] = '代收款合计'
        } else {
          if (column.property === 'money') {
            let temp = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = decimalNumFilter(temp, (column.property === 'num' || column.property === 'packNum') ? 0 : 2)
          } else {
            sums[index] = ''
          }
        }
      })
      return sums
    },
    // 费用合计
    getSummariesCostList(param) {
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]))
        if (index === 0) {
          sums[index] = '合计'
        } else {
          if (column.property === 'money') {
            let temp = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = decimalNumFilter(temp, 2)
          } else {
            sums[index] = ''
          }
        }
      })
      return sums
    },
    getTempDetail() { // 暂存单详情
      this.initLoading = true
      this.$ajax.get('/ms-warehouse-order/orderTemp/getFwOrderTempDetail', {id: this.id}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          // 初始化
          const productParameterList = dotData(response, 'data.productParameterList') || []
          // 产品信息添加 产品大小类
          this.model.productParameterList = productParameterList.map(v => {
            if (v.middleClass && v.middleClassNo) {
              v.optionsMiddle = [{text: v.middleClass, value: v.middleClassNo}]
            }
            if (v.bigClass && v.bigClassNo) {
              v.optionsBig = [{text: v.bigClass, value: v.bigClassNo}]
            }
            return v
          })
          this.model.storageType = dotData(response, 'data.chOrderService.storageTypeCode')
          // 商家
          if (dotData(response, 'data.chOrderService.cargoOwnerId')) {
            this.cargoOwnerArr = [{
              text: dotData(response, 'data.chOrderService.cargoOwner'),
              value: dotData(response, 'data.chOrderService.cargoOwnerId')
            }]
          }
          this.model.cargoOwnerId = dotData(response, 'data.chOrderService.cargoOwnerId')
          this.model.serviceList = dotData(response, 'data.serviceList')
          this.model.consigneName = dotData(response, 'data.chOrderConsigneeInfoTemp.consigneName')
          this.model.consignePhone = dotData(response, 'data.chOrderConsigneeInfoTemp.consignePhone')
          this.model.floor = dotData(response, 'data.chOrderConsigneeInfoTemp.floor')
          this.model.consigneMemo = dotData(response, 'data.chOrderConsigneeInfoTemp.consigneMemo')
          this.model.consigneAddress = dotData(response, 'data.chOrderConsigneeInfoTemp.consigneAddress')
          this.model.outNo = dotData(response, 'data.chOrderService.outNo')
          this.orderSourceNo = dotData(response, 'data.chOrderService.orderSourceNo')
          this.model.outSourceWarehouse = dotData(response, 'data.chOrderService.outSourceWarehouse')
          this.model.memo = dotData(response, 'data.chOrderService.memo')
          this.model.elevator = dotData(response, 'data.chOrderConsigneeInfoTemp.elevator')
          // 客户地址
          let addressArr = []
          if (dotData(response, 'data.chOrderConsigneeInfoTemp.consigneProvinceNo')) {
            addressArr.push(dotData(response, 'data.chOrderConsigneeInfoTemp.consigneProvinceNo'))
            if (dotData(response, 'data.chOrderConsigneeInfoTemp.consigneCityNo')) {
              addressArr.push(dotData(response, 'data.chOrderConsigneeInfoTemp.consigneCityNo'))
              if (dotData(response, 'data.chOrderConsigneeInfoTemp.consigneDistrictNo')) {
                addressArr.push(dotData(response, 'data.chOrderConsigneeInfoTemp.consigneDistrictNo'))
              }
            }
          }
          this.model.addressArr = addressArr
          // 费用
          this.model.costList = dotData(response, 'data.costList') || []
          // 产品类型
          this.model.productType = dotData(response, 'data.chOrderService.productType') || 1
          let PickUpInfoAddress = []
          if (dotData(response, 'data.orderPickUpInfo.pickUpProvinceNo')) {
            PickUpInfoAddress.push(dotData(response, 'data.orderPickUpInfo.pickUpProvinceNo'))
            if (dotData(response, 'data.orderPickUpInfo.pickUpCityNo')) {
              PickUpInfoAddress.push(dotData(response, 'data.orderPickUpInfo.pickUpCityNo'))
              if (dotData(response, 'data.orderPickUpInfo.pickUpDistrictNo')) {
                PickUpInfoAddress.push(dotData(response, 'data.orderPickUpInfo.pickUpDistrictNo'))
              }
            }
          }
          this.model.orderPickUpInfo = {
            pickUpAddress: dotData(response, 'data.orderPickUpInfo.pickUpAddress'),
            addressArr: PickUpInfoAddress,
            pickUpMemo: dotData(response, 'data.orderPickUpInfo.pickUpMemo'),
            pickUpName: dotData(response, 'data.orderPickUpInfo.pickUpName'),
            pickUpPhone: dotData(response, 'data.orderPickUpInfo.pickUpPhone')
          }
          // 代收款费用信息
          this.model.chServiceCollectionCostList = []
          let chServiceCollectionCostList = dotData(response, 'data.chServiceCollectionCostList', [])
          this.model.chServiceCollectionCostList = chServiceCollectionCostList || []
          // 预约时间
          this.model.appointTime = dotData(response, 'data.appointTime')
          this.model.appointTimePart = dotData(response, 'data.appointTimePart')
          // 仓库
          this.model.warehouseId = dotData(response, 'data.chOrderService.warehouseId')
          // 核销类型
          this.model.verifitySource = dotData(response, 'data.verifitySource')
          // 核销单号
          let verifityNoList = dotData(response, 'data.verifityNoList') || []
          if (Array.isArray(verifityNoList)) {
            this.model.verifityNoList = verifityNoList.map(v => {
              return {code: v.tradeCode}
            })
          } else {
            this.model.verifityNoList = [{code: ''}]
          }
          // isStorage 是否有仓库
          this.model.isStorage = dotData(response, 'data.chOrderService.isStorage') || 0
          // 总体积
          this.model.allVolume = dotData(response, 'data.chOrderService.totalVolume') || ''
          // 业务类型
          this.model.businessNo = dotData(response, 'data.chOrderService.businessNo') || ''
          this.model.orderSourceNo = dotData(response, 'data.chOrderService.orderSourceNo') || ''

          // 总重量
          this.model.allWeight = dotData(response, 'data.chOrderService.allWeight') || dotData(response, 'data.chOrderService.totalWeight')
          // 接单价
          this.model.pickOrderMoney = dotData(response, 'data.chOrderService.pickOrderMoney') || ''
          // 总货值
          this.model.cargoPrice = dotData(response, 'data.chOrderService.cargoPrice') || ''
        }
      }).then(_ => {
        this.afterHttpGetDetail()
      }).finally(_ => {
        this.initLoading = false
      })
    },
    getOrderDetail() { // 正式订单详情
      this.initLoading = true
      this.$ajax.get('/ms-terminal-order/orderData/getOrderDatails', {orderId: this.id}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          // 初始化
          let productExtBeans = dotData(response, 'data.productExtBeans') || []
          this.model.productParameterList = productExtBeans.map(v => { // 详情接口返回的数据和新增的不统一 进行映射
            v.manufacturersName = v.manufacturerName
            v.packBuildNum = v.proudctPackNum / (parseInt(v.proudctNum) || 1) // 此处后端返回的是包件和，处理为单个
            v.packNum = v.proudctPackNum
            v.num = v.proudctNum
            if (v.middleClass && v.middleClassNo) {
              v.optionsMiddle = [{text: v.middleClass, value: v.middleClassNo}]
            }
            if (v.bigClass && v.bigClassNo) {
              v.optionsBig = [{text: v.bigClass, value: v.bigClassNo}]
            }
            return v
          })
          this.model.storageType = dotData(response, 'data.chOrder.storageTypeCode')
          this.model.cargoOwnerId = dotData(response, 'data.chOrder.cargoOwnerId')
          this.model.businessNo = dotData(response, 'data.chOrder.businessNo')
          let serviceList = dotData(response, 'data.chOrder.serviceNo')
          this.model.serviceList = serviceList ? serviceList.split(',') : []
          this.model.consigneName = dotData(response, 'data.chOrderConsigneeInfo.consigneName')
          this.model.consignePhone = dotData(response, 'data.chOrderConsigneeInfo.consignePhone')
          this.model.floor = dotData(response, 'data.chOrderConsigneeInfo.floor')
          this.model.consigneMemo = dotData(response, 'data.chOrderConsigneeInfo.consigneMemo')
          this.model.consigneAddress = dotData(response, 'data.chOrderConsigneeInfo.consigneAddress')
          this.model.outNo = dotData(response, 'data.chOrder.outNo')
          this.model.outSourceWarehouse = dotData(response, 'data.chOrder.outSourceWarehouse')
          this.model.memo = dotData(response, 'data.chOrder.memo')
          this.model.elevator = dotData(response, 'data.chOrderConsigneeInfo.elevator')
          // 客户地址
          let addressArr = []
          if (dotData(response, 'data.chOrderConsigneeInfo.consigneProvinceNo')) {
            addressArr.push(dotData(response, 'data.chOrderConsigneeInfo.consigneProvinceNo'))
            if (dotData(response, 'data.chOrderConsigneeInfo.consigneCityNo')) {
              addressArr.push(dotData(response, 'data.chOrderConsigneeInfo.consigneCityNo'))
              if (dotData(response, 'data.chOrderConsigneeInfo.consigneDistrictNo')) {
                addressArr.push(dotData(response, 'data.chOrderConsigneeInfo.consigneDistrictNo'))
              }
            }
          }
          this.model.addressArr = addressArr
          // 商家
          if (dotData(response, 'data.chOrder.cargoOwnerId')) {
            this.cargoOwnerArr = [{
              text: dotData(response, 'data.chOrder.cargoOwner'),
              value: dotData(response, 'data.chOrder.cargoOwnerId')
            }]
          }
          this.model.cargoOwnerName = dotData(response, 'data.chOrder.cargoOwner') || ''
          // 费用
          this.model.costList = dotData(response, 'data.orderCosts') || []
          // 产品类型
          this.model.productType = dotData(response, 'data.chOrder.productType') || 1
          let PickUpInfoAddress = []
          if (dotData(response, 'data.chOrder.pickUpProvinceNo')) {
            PickUpInfoAddress.push(dotData(response, 'data.chOrder.pickUpProvinceNo'))
            if (dotData(response, 'data.chOrder.pickUpCityNo')) {
              PickUpInfoAddress.push(dotData(response, 'data.chOrder.pickUpCityNo'))
              if (dotData(response, 'data.chOrder.pickUpDistrictNo')) {
                PickUpInfoAddress.push(dotData(response, 'data.chOrder.pickUpDistrictNo'))
              }
            }
          }
          this.model.orderPickUpInfo = {
            pickUpAddress: dotData(response, 'data.chOrder.pickUpAddress'),
            addressArr: PickUpInfoAddress,
            pickUpMemo: dotData(response, 'data.chOrder.pickUpMemo'),
            pickUpName: dotData(response, 'data.chOrder.pickUpName'),
            pickUpPhone: dotData(response, 'data.chOrder.pickUpPhone')
          }
          // 代收款费用信息
          this.model.chServiceCollectionCostList = []
          let chServiceCollectionCostList = dotData(response, 'data.chServiceCollectionCostList', [])
          this.model.chServiceCollectionCostList = chServiceCollectionCostList || []
          // 预约时间
          let start = dotData(response, 'data.chServiceAppointmentDispatch.start')
          this.model.appointTime = start ? unixTimestampFilter(start, 'YYYY-MM-DD') : ''
          this.model.appointTimePart = dotData(response, 'data.chServiceAppointmentDispatch.timeIntervalCode')
          // 仓库
          this.model.warehouseId = dotData(response, 'data.chOrder.warehouseId')
          // 核销类型
          this.model.verifitySource = dotData(response, 'data.verifitySource') || ''
          // 核销单号
          let verifityNoList = dotData(response, 'data.verifityNoList') || []
          if (Array.isArray(verifityNoList) && verifityNoList.length > 0) {
            this.model.verifityNoList = verifityNoList.map(v => {
              return {code: v.tradeCode}
            })
          } else {
            this.model.verifityNoList = [{code: ''}]
          }
          // 是否有仓库
          this.model.isStorage = dotData(response, 'data.chOrder.isStorage') || 0
          // 总体积
          this.model.allVolume = dotData(response, 'data.chOrder.totalVolume') || ''
          // 总重量
          this.model.allWeight = dotData(response, 'data.chOrder.allWeight') || dotData(response, 'data.chOrder.totalWeight')
          // 接单价
          this.model.pickOrderMoney = dotData(response, 'data.chOrder.pickOrderMoney') || ''
          return response
        }
      }).then(_ => {
        this.afterHttpGetDetail()
      }).finally(_ => {
        this.initLoading = false
      })
    },
    // 获取商城订单服务单详情
    getStoreOrderDetail() {
      this.initLoading = true
      this.$ajax.get('/ms-warehouse-store/order/get-store-order-details', {mallOrderId: this.id}).then(response => {
        const success = response.success
        if (success) {
          this.mallOrderId = dotData(response, 'data.mallOrderId')
          // 商家
          if (dotData(response, 'data.cargoOwnerId')) {
            this.cargoOwnerArr = [{
              text: dotData(response, 'data.cargoOwnerName'),
              value: dotData(response, 'data.cargoOwnerId')
            }]
          }
          this.model.cargoOwnerId = dotData(response, 'data.cargoOwnerId')
          // 业务类型
          this.model.businessNo = dotData(response, 'data.businessNo')
          // 服务类型
          this.model.serviceList = dotData(response, 'data.serviceNo')
          // 商品信息
          const productParameterList = dotData(response, 'data.productList') || []
          this.model.productParameterList = productParameterList.map(v => {
            return v
          })
          // 客户信息
          this.model.consigneName = dotData(response, 'data.consigneName')
          this.model.consignePhone = dotData(response, 'data.consignePhone')
          this.model.consigneMemo = dotData(response, 'data.consigneMemo')
          this.model.consigneAddress = dotData(response, 'data.consigneAddress')
          // 客户地址
          let addressArr = []
          if (dotData(response, 'data.consigneProvinceNo')) {
            addressArr.push(dotData(response, 'data.consigneProvinceNo'))
            if (dotData(response, 'data.consigneCityNo')) {
              addressArr.push(dotData(response, 'data.consigneCityNo'))
              if (dotData(response, 'data.consigneDistrictNo')) {
                addressArr.push(dotData(response, 'data.consigneDistrictNo'))
              }
            }
          }
          this.model.addressArr = addressArr
        }
      }).then(_ => {
        this.afterHttpGetDetail()
      }).finally(_ => {
        this.initLoading = false
      })
    },
    // 获取详情后还是要做的后续操作
    afterHttpGetDetail() {
      if (this.model.storageType) {
        getMyWarehouse(this.model.storageType).then(arr => {
          this.warehouseIdArr = arr
        })
      }
      // 触发服务类型
      this.setServiceArr().then(_ => {
        // 触发费用信息
        console.log(this.checkedServiceTypeCostList, 'this.checkedServiceTypeCostList')
        this.setModelFee(this.checkedServiceTypeCostList)
      })
      // 触发模块信息
      this.setModuleIf()
    },
    // 添加核销单号
    pushVerifityNoList() {
      this.model.verifityNoList.push({code: ''})
    },
    // 删除核销单号
    removeVerifityNoList(index) {
      if (this.model.verifityNoList.length === 1) {
        alert('必须要有核销单号')
        return
      }
      this.model.verifityNoList.splice(index, 1)
    },
    // 获取服务类型
    setServiceArr() {
      if (this.model.businessNo && [1, 0].indexOf(this.model.isStorage) >= 0) {
        if (this.model.isStorage === 1) { // 有仓库就要仓库类型
          if (!this.model.storageType) {
            return
          }
        }
        let storageType = this.model.storageType
        // 无仓库清空服务类型1
        if (this.model.isStorage === 0) {
          storageType = ''
        }
        return getOmsCreateServiceList(this.model.businessNo, this.model.isStorage, storageType).then(arr => {
          this.serviceArr = arr
        }).then(_ => {
          // 清空不存在的服务类型
          if (Array.isArray(this.serviceArr)) {
            const serviceCodeArr = this.serviceArr.map(v => v.serviceTypeCode)
            this.model.serviceList = this.model.serviceList.filter(v => serviceCodeArr.indexOf(v) >= 0)
          }
        })
      } else {
        return Promise.resolve([])
      }
    },
    // 获取展示模块
    setModuleIf() {
      if (this.isStoreOrder) { // 商城订单直接由商城控制，不需要请求
        return
      }
      if (this.model.businessNo && Array.isArray(this.model.serviceList) && this.model.serviceList.length > 0) {
        getOmsModuleIf(this.model.businessNo, this.model.serviceList).then(data => {
          if (Array.isArray(data)) {
            this.modules = data
          } else {
            alert('模块展示接口期望是数组')
          }
        })
      }
    },
    // 模块展示控制
    ifModule(moduleCode) {
      // 如果商城直接
      if (this.isStoreOrder) {
        return ['goods', 'consigneeInfo', 'pickUpInfo', 'costInfo', 'otherInfo'].indexOf(moduleCode) >= 0
      }
      if (Array.isArray(this.modules)) {
        return this.modules.map(v => v.modelCode).indexOf(moduleCode) >= 0
      }
      return true
    },
    // 建议体积
    suggestAllVolume() {
      if (this.totalVolume) {
        this.model.allVolume = decimalNumFilter(this.totalVolume)
      } else {
        alert('建议体积要是大于0的数字')
      }
    },
    // 跳转到交易管理
    toStoreIndex() {
      this.$router.push({path: '/redirect/ss-oms/shop/trade'})
    },
    // 处理商家名称建议输入
    handleCargoOwnerNameSelect(item) {
      const cargoOwnerId = dotData(item, 'cargoOwnerId')
      if (cargoOwnerId) {
        this.model.cargoOwnerId = cargoOwnerId
      }
    },
    // 触发商家设置
    blurSetCargoOwnerName() {
      this.blurSetCargoOwnerNameDebounce(this)
    },
    // 放抖商家设置
    blurSetCargoOwnerNameDebounce: L.debounce((_this) => {
      if (_this.model.cargoOwnerName) {
        _this.$ajax.get('/ms-warehouse-order/WhPackage/findCargoOwnerByFullName', {fullName: _this.model.cargoOwnerName}).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            const data = dotData(response, 'data')
            if (data.cargoOwnerId) {
              _this.model.cargoOwnerId = data.cargoOwnerId
              _this.autoCompleteCargoOwnerNameSuggest = ''
            } else {
              _this.autoCompleteCargoOwnerNameSuggest = '商家不存在，会在录单后新增该商家'
            }
          }
        }).catch(_ => {
          _this.autoCompleteCargoOwnerNameSuggest = '商家不存在，会在录单后新增该商家'
        })
      }
    }, 1000)
  }
}
</script>
